//引入公共函数
var util = require('../../utils/util');

//引入md5算法模块
var md5 = require('../../utils/md5');

//获得发起请求的URL
var requestDomain = util.config('requestDomain');

//存放页面实例的变量
var that;

//页面Page函数
Page({

  //页面数据
  data:{

    //选择的菜品列表数组
    selectedFoodList: [],

    //附加物品列表数组
    attachGoodsList: [],

    checkedAttachGoodsList: [],

    //优惠券列表数组
    couponList: [],

    //菜品总计金额
    payTotal: 0,

    //是否禁用立即支付按钮
    payBtnDisabled: false,

    waitCashPayDone: false,

    cashPayBtnDisabled: false,

    cashPayOrderId: ''

  },

  /**
   * 页面加载时触发
   */

  onLoad:function(options){
    
    //存放页面实例
    that = this;

    //设置标题为商户名称
    wx.setNavigationBarTitle({
        title: util.globalData('tableNum') + '桌 | 订单列表',
    });

    //设置附加物品列表
    that.setData({attachGoodsList: util.globalData('attachGoodsList')});

  },

  /**
   * 页面显示时触发
   */

  onShow:function(){
    
    //触发更新订单列表函数
    that.updateOrderList();

  },

  changeAttachGoodsCheckStatus: function(e) {

    let {goodsid} = e.currentTarget.dataset;

    let {attachGoodsList} = that.data;

    for(let goodsIndex in attachGoodsList) {
      
      if(attachGoodsList[goodsIndex].goodsId == goodsid) {

        attachGoodsList[goodsIndex].goodsChecked = !attachGoodsList[goodsIndex].goodsChecked;

        break;

      }
    }

    that.updateOrderList();

    that.setData({attachGoodsList: attachGoodsList});

  },

  /**
   * 显示订单菜品的操作菜单
   */

  showOrderUseMenu: function(e) {
    let foodId = e.currentTarget.id;
    wx.showActionSheet({
      itemList: ['移除此菜品', '取消'],
      success: function(result) {
        switch(result.tapIndex) {
          case 0: 
            that.removeOrderFood(foodId);
          break;
        }
      }
    });
  },

  /**
   * 移除选择的某个菜品函数
   */

  removeOrderFood: function(foodId) {
    let {selectedFoodList} = that.data;
    console.log(selectedFoodList);
    for(let foodIndex in selectedFoodList) {
      if(selectedFoodList[foodIndex].foodId == foodId) {
        selectedFoodList.splice(foodIndex, 1);
      }
    }
    
    that.updateOrderList(selectedFoodList);
    util.globalData('selectedFoodData', selectedFoodList);
  },

  /**
   * 点击立即支付按钮触发函数
   */

  payGoods: function() {

    //获得选择的菜品列表数据
    let {selectedFoodList, checkedAttachGoodsList} = that.data;

    //判断菜品列表数据是否合法
    if(selectedFoodList.length > 0 && selectedFoodList[0].foodId && selectedFoodList[0].foodId.length > 0 && selectedFoodList[0].count > 0) {

      //显示支付方式选择器
      wx.showActionSheet({

        //支付选项列表
        itemList: ['微信支付（推荐）', '现金支付'],

        //已选择
        success: function(result) {
          
          that.setData({payBtnDisabled: true});

          //判断选择了什么支付方式
          switch(result.tapIndex) {

            //微信支付
            case 0:

              //调用微信支付函数
              that.wxPay(selectedFoodList, checkedAttachGoodsList);
              
            break;

            //现金支付
            case 1: 

              //调用现金支付函数
              that.cashPay(selectedFoodList, checkedAttachGoodsList);

            break;

            //其它情况解除支付按钮禁用状态
            default: that.setData({payBtnDisabled: false});

          }
        }
      });

    }
    else {

      //订单列表数据异常显示错误
      util.showError('提交订单失败', '抱歉，您未正确的选择菜品，此订单将无法提交，请重试');

      //发生错误就清空订单列表
      that.setData({selectedFoodList: []});

    }
  },

  /**
   * 更新订单列表函数
   */

  updateOrderList: function(data) {

    //获得选择的菜品数据
    let selectedFoodData = data || util.globalData('selectedFoodData');

    //更新选择的菜品数据到界面
    that.setData({"selectedFoodList": selectedFoodData});

    //获得选择的菜品列表
    let {selectedFoodList, attachGoodsList} = that.data;

    //订单总额变量
    let payTotal = 0;

    //遍历选择的菜品列表数组
    for(var selectedFoodIndex in selectedFoodList){

      //将每个菜品的价格x数量的总价格添加进总计价格中
      payTotal += parseInt(selectedFoodList[selectedFoodIndex].foodPrice) * parseInt(selectedFoodList[selectedFoodIndex].count);

    }

    let checkedAttachGoodsList = [];

    //将每个附加物品的价格x数量的总价格添加进总计价格中
    for(let attachGoodsIndex in attachGoodsList) {

      if(attachGoodsList[attachGoodsIndex].goodsForce || attachGoodsList[attachGoodsIndex].goodsChecked) {
        
        payTotal += parseInt(attachGoodsList[attachGoodsIndex].goodsPrice) * parseInt(attachGoodsList[attachGoodsIndex].goodsCount);

        checkedAttachGoodsList.push({
          goodsId: attachGoodsList[attachGoodsIndex].goodsId
        });
      }
    }

    //存放已勾选的附加物品列表
    that.data.checkedAttachGoodsList = checkedAttachGoodsList;

    //将总金额更新到界面显示
    that.setData({payTotal: payTotal});

    wx.stopPullDownRefresh();
  },

  /**
   * 微信支付函数
   */

  wxPay: function(payGoods, attachGoods) {

    //显示顶部加载图标
    wx.showNavigationBarLoading();

    //获得商户数据
    var storeData = util.globalData('storeData');

    //发起创建订单请求
    wx.request({

      //创建订单接口
      url: requestDomain + 'pay/wxPay',
      
      //创建订单接口所需数据
      data: {

        //商户ID
        storeId: storeData.storeId,

        tableNum: util.globalData('tableNum'),

        //验证用户身份的session
        _3rdSession: util.globalData('_3rdSession'),
        
        //购买的菜品列表
        payGoods: payGoods,

        //附带物品列表
        attachGoods: attachGoods
        
      },

      method: 'POST',
      
      //请求成功
      success: function(result){

        //判断接口请求是否成功
        if(util.checkSuccess(result) && result.data && result.data.data) {

          //显示顶部加载图标
          wx.showNavigationBarLoading();

          //获得返回的预支付订单ID
          result = result.data.data;

          if(result.orderId && result.timeStamp && result.nonceStr && result.package && result.signType && result.paySign) {
            //发起支付请求
            wx.requestPayment({

              //当前时间戳
              timeStamp: result.timeStamp,

              //随机字符串
              nonceStr: result.nonceStr,

              //prepay_id数据包
              package: result.package,

              //验证的算法类型，默认MD5
              signType: result.signType,

              //验证签名的字符串
              paySign: result.paySign,

              //支付成功
              success: function(payResult){

                console.log(payResult, result.orderId);

                //隐藏顶部加载图标
                wx.hideNavigationBarLoading();

                //显示支付成功
                wx.showToast({
                  title: '支付成功',
                  icon: 'success'
                });
                
                //清空订单列表
                that.updateOrderList([]);
                util.globalData('selectedFoodData', []);

                //解除支付按钮的禁用状态
                that.setData({payBtnDisabled: false});

              },

              //支付失败
              fail: function(err) {

                //隐藏顶部加载图标
                wx.hideNavigationBarLoading();

                //解除支付按钮禁用状态
                that.setData({payBtnDisabled: false});

                //显示支付失败的错误
                util.showError('支付失败', '您可能未完成支付操作');

              }
            });
          }
          else {

            //隐藏顶部加载图标
            wx.hideNavigationBarLoading();

            //解除支付按钮禁用状态
            that.setData({payBtnDisabled: false});

            wx.showModal({
              title: '数据校验错误',
              content: '订单数据校验错误，请重试'
            });
          }
        }
        else {

          //隐藏顶部加载图标
          wx.hideNavigationBarLoading();

          //解除支付按钮禁用状态
          that.setData({payBtnDisabled: false});
          
          //显示创建订单失败
          util.showError('创建订单失败', '服务器在处理订单操作时失败', result.data.errCode, result.data.errMsg);

        }
      },

      //请求失败
      fail: function() {
        
        //隐藏顶部加载图标
        wx.hideNavigationBarLoading();

        //解除支付按钮禁用状态
        that.setData({payBtnDisabled: false});

        //显示发起订单请求失败
        util.showError('提交失败', '发起订单请求失败');

      }
    });   
  },

  /**
   * 现金支付函数
   */

  cashPay: function (payGoods, attachGoods) {
    wx.showNavigationBarLoading();
    wx.request({
        url: requestDomain + 'pay/cashPay',
        method: 'POST',
        data: {
            storeId: util.globalData('storeId'),

            _3rdSession: util.globalData('_3rdSession'),
            //支付的菜品列表
            payGoods: payGoods,
            //支付的附加物品列表
            attachGoods: attachGoods,
            //发起支付的桌号
            tableNum: util.globalData('tableNum')
        },
        success: function(result) {
            wx.hideNavigationBarLoading();
            console.log(result);
            if(util.checkSuccess(result) && result.data && result.data.data) {
                result = result.data.data;
                console.log(result);
                if(!result.orderId) {
                    //解除支付按钮禁用状态
                    that.setData({ payBtnDisabled: false });
                    wx.showModal({
                        title: '无法现金支付',
                        content: '您尚未付清上次现金支付的订单，请确认店家是否确认收款',
                        cancelText: '我有疑问',
                        success: function(modal) {
                            if(!modal.confirm) {
                                //对无法支付有疑问
                            }
                        }
                    })
                }
                else {
                    console.log(result.orderId);
                    that.data.cashPayOrderId = result.orderId;
                    that.setData({
                        waitCashPayDone: true
                    });
                }
            }
            else {
                //解除支付按钮禁用状态
                that.setData({ payBtnDisabled: false });
                util.showError('支付失败', '在处理现金支付请求时出现错误' + result.data.errMsg, result.data.errCode);
            }
        },
        fail: function() {
            wx.hideNavigationBarLoading();

            //解除支付按钮禁用状态
            that.setData({ payBtnDisabled: false });

            util.showError('支付失败', '发起现金支付请求出现错误');
        }
    });
  },

  cashPayDone: function() {
      let {cashPayOrderId} = that.data;
      if (cashPayOrderId == '') {
        util.showError('操作错误', '未获取现金支付的订单ID');
        return;
      }
      wx.showNavigationBarLoading();
      that.setData({ cashPayBtnDisabled: true });
      wx.request({
          url: requestDomain + 'pay/checkCashPayDone',
          method: 'POST',
          data: {
              storeId: util.globalData('storeId'),
              _3rdSession: util.globalData('_3rdSession'),
              orderId: cashPayOrderId
          },
          success: function(result) {
            wx.hideNavigationBarLoading();
            if(util.checkSuccess(result) && result.data && result.data.data) {
                wx.showToast({
                    title: '支付成功',
                    icon: 'success'
                });
                that.setData({
                    waitCashPayDone: false
                });

                //清空订单列表
                that.updateOrderList([]);
                util.globalData('selectedFoodData', []);

                //解除支付按钮的禁用状态
                that.setData({ cashPayBtnDisabled: false, payBtnDisabled: false });
            }
            else if(util.checkSuccess(result, ['-0189'])) {
                wx.hideNavigationBarLoading();
                that.setData({ cashPayBtnDisabled: false });
                wx.showModal({
                    title: '商家还未确认收款',
                    content: '请等待商家收款完毕再点击此按钮'
                });
            }
            else {
                wx.hideNavigationBarLoading();
                that.setData({ cashPayBtnDisabled: false });
                util.showError('确认失败', '确认现金支付失败' + result.data.errMsg, result.data.errCode);
            }
          },
          fail: function() {
            wx.hideNavigationBarLoading();
            that.setData({ cashPayBtnDisabled: false });
            util.showError('确认失败', '发起确认现金支付请求失败');
          }
      });
  },

  onPullDownRefresh: function() {
      that.setData({ attachGoodsList: util.globalData('attachGoodsList') });
      that.updateOrderList();
  }

});